﻿@namespace Blazorise.Docs.Docs.Examples
@using Microsoft.Extensions.Options
@using System.Text.Json

<Div Flex="Flex.AlignItems.Center" Gap="Gap.Is3">
    <Captcha @ref="@captcha" Solved="@Solved" Validate="@Validate" Expired="Expired" />

    <Button Background="Background.Primary" Clicked="@Reset">
        Reset
    </Button>
</Div>

@code {
    [Inject] IOptions<AppSettings> AppSettings { get; set; }

    [Inject] IHttpClientFactory HttpClientFactory { get; set; }

    private Captcha captcha;

    private void Solved( CaptchaState state )
    {
        Console.WriteLine( $"Captcha Success: {state.Valid}" );
    }

    private void Expired()
    {
        Console.WriteLine( "Captcha Expired" );
    }

    private async Task<bool> Validate( CaptchaState state )
    {
        Console.WriteLine( "Captcha Validate" );

        //Perform server side validation
        //You should make sure to implement server side validation
        //https://developers.google.com/recaptcha/docs/verify
        //Here's a simple example:
        var content = new FormUrlEncodedContent( new[]
        {
            new KeyValuePair<string, string>("secret", AppSettings.Value.ReCaptchaServerKey),
            new KeyValuePair<string, string>("response", state.Response),
         } );

        var httpClient = HttpClientFactory.CreateClient();
        var response = await httpClient.PostAsync( "https://www.google.com/recaptcha/api/siteverify", content );

        var result = await response.Content.ReadAsStringAsync();
        var googleResponse = JsonSerializer.Deserialize<GoogleResponse>( result, new JsonSerializerOptions()
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            } );

        return googleResponse.Success;
    }

    private async Task Reset()
    {
        await captcha.Reset();
    }

    public class GoogleResponse
    {
        public bool Success { get; set; }
        public double Score { get; set; } //V3 only - The score for this request (0.0 - 1.0)
        public string Action { get; set; } //v3 only - An identifier
        public string Challenge_ts { get; set; }
        public string Hostname { get; set; }
        public string ErrorCodes { get; set; }
    }
}